`timescale 1ns / 1ps

// 水平读出模块
// 水平读出模块所需要的时钟比较特殊，为了确保在每一个像元周期内，ADC采样点的位置都是固定不变的，就需要用
// 与ADC输出的时钟同源的时钟信号

module hTrans(
    input       clk_h,          // 250MHz
    input       clk_reg,        // clk_reg与像元周期对应
    input       clk_reg_half,   // 频率为clk_reg的一半，用来分别使能nt1/cnt2
    input       htrans_en,
    input[31:0] ccd_phi1_A,
    input[31:0] ccd_phi1_B,
    input[31:0] ccd_phi2_A,
    input[31:0] ccd_phi2_B,
    input[31:0] ccd_phi3_A,
    input[31:0] ccd_phi3_B,
    input[31:0] ccd_rst_A,
    input[31:0] ccd_rst_B,

    output reg  ccd_phi1,
    output reg  ccd_phi2,
    output reg  ccd_phi3,
    output reg  ccd_rst
    );

reg [31:0] cnt1 = 32'd0;
reg [31:0] cnt2 = 32'd0;

always@( posedge clk_h ) begin
    if( ~clk_reg_half & htrans_en ) begin
        cnt1 <= cnt1 + 32'd1;
    end
    else begin
        cnt1 <= 32'd0;
    end
end

assign ccd_phi1_1 = (cnt1 > ccd_phi1_A) && (cnt1 < ccd_phi1_B);
assign ccd_phi2_1 = (cnt1 > ccd_phi2_A) && (cnt1 < ccd_phi2_B);
assign ccd_phi3_1 = (cnt1 > ccd_phi3_A) && (cnt1 < ccd_phi3_B);
assign ccd_rst_1  = (cnt1 > ccd_rst_A ) && (cnt1 < ccd_rst_B );


always@( posedge clk_h ) begin
    if( clk_reg_half & htrans_en ) begin
        cnt2 <= cnt2 + 32'd1;
    end
    else begin
        cnt2 <= 32'd0;
    end
end

assign ccd_phi1_2 = (cnt2 > ccd_phi1_A) && (cnt2 < ccd_phi1_B);
assign ccd_phi2_2 = (cnt2 > ccd_phi2_A) && (cnt2 < ccd_phi2_B);
assign ccd_phi3_2 = (cnt2 > ccd_phi3_A) && (cnt2 < ccd_phi3_B);
assign ccd_rst_2  = (cnt2 > ccd_rst_A ) && (cnt2 < ccd_rst_B );

always@(*) begin
    if( htrans_en ) begin
        // ccd_phi1 = ~(ccd_phi1_1 || ccd_phi1_2);
        // ccd_phi2 =  (ccd_phi2_1 || ccd_phi2_2);
        // ccd_phi3 = ~(ccd_phi3_1 || ccd_phi3_2);
        // ccd_rst  = ~(ccd_rst_1 || ccd_rst_2);

        ccd_phi1 = (ccd_phi1_1 || ccd_phi1_2);
        ccd_phi2 =~(ccd_phi2_1 || ccd_phi2_2);
        ccd_phi3 = (ccd_phi3_1 || ccd_phi3_2);
        ccd_rst  = (ccd_rst_1 || ccd_rst_2);
    end
    else begin
        ccd_phi1 = 1'b0;
        ccd_phi2 = 1'b0;
        ccd_phi3 = 1'b1;
        ccd_rst  = 1'b1;
    end
end

endmodule
